package kr.haggenna.sevice.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import kr.haggenna.branch.dao.BranchDao;
import kr.haggenna.branch.domain.Branch;
import kr.haggenna.member.dao.MemberDao;
import kr.haggenna.member.domain.MemberCommand;
import kr.haggenna.sevice.dao.ServiceDao;
import kr.haggenna.sevice.domain.ServiceCommand;
import kr.haggenna.sevice.validator.ServiceValidator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ServiceInputController {
	
	@Autowired
	private ServiceDao serviceDao;
	
	@Autowired
	private MemberDao memberDao;
	
	@Autowired
	private BranchDao branchDao;
	
	public void setServiceDao(ServiceDao serviceDao){
		this.serviceDao = serviceDao;
	}
	
	@RequestMapping(value="/serviceInput.do",method=RequestMethod.GET)
	public ModelAndView form(HttpSession session){
		
		List<Branch> branchList = branchDao.getBranchList();
		
		String email = (String)session.getAttribute("email");
		MemberCommand memberCommand = memberDao.getMember(email);
		String member_name = memberCommand.getName();
		String member_email = memberCommand.getEmail();
		String member_phone = memberCommand.getPhone();
		
		ModelAndView mav = new ModelAndView();
		
		mav.setViewName("serviceInput");
		mav.addObject("branchList", branchList);
		mav.addObject("member_name", member_name);
		mav.addObject("member_email", member_email);
		mav.addObject("member_phone", member_phone);
		
		return mav;
		
	}
	
	@ModelAttribute
	public ServiceCommand formBacking(){
		return new ServiceCommand();
	}
	
	@RequestMapping(value="/inputPro.do",method=RequestMethod.POST)
	public ModelAndView submit(@ModelAttribute("serviceCommand")ServiceCommand serviceCommand,BindingResult result,HttpSession session){
		
		MemberCommand memberCommand = memberDao.getMember((String)session.getAttribute("email"));
		serviceCommand.setName(memberCommand.getName());
		serviceCommand.setPhone(memberCommand.getPhone());
		
		ModelAndView mav = new ModelAndView();
		
		new ServiceValidator().validate(serviceCommand, result);
		
		if(result.hasErrors()){
			return form(session);
		}
		
		serviceDao.insertService(serviceCommand);
		mav.setViewName("redirect:/serviceList.do");
		
		return mav;
	}
	
	
}
